package com.ruoyi.voucher.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ruoyi.voucher.domain.Voucher;
import com.ruoyi.voucher.mapper.VocherMapper;
import java.util.ArrayList;
import java.util.List;

public class VoucherDataListener extends AnalysisEventListener<Voucher> {

    private static final int BATCH_COUNT = 100;
    private List<Voucher> cachedDataList = new ArrayList<>(BATCH_COUNT);
    private VocherMapper vocherMapper;

    public VoucherDataListener(VocherMapper vocherMapper) {
        this.vocherMapper = vocherMapper;
    }

    @Override
    public void invoke(Voucher voucher, AnalysisContext analysisContext) {
        cachedDataList.add(voucher);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        cachedDataList.clear();
    }

    private void saveData() {
        if (cachedDataList.isEmpty()) {
            return;
        }
        vocherMapper.batchInsertVoucher(cachedDataList);
    }
}